package com.uoko.common.serializable;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author xianguo
 * Email xianguo@uoko.com
 * created by 2018/6/7 0007
 */
public class TextUtil {
    /**
     * 读取文本文件的信息
     * @param filePath 文件地址
     * @return txt文件的String集合
     */
    public static List<String> readTxt(String filePath){
        InputStreamReader reader = null;
        BufferedReader bufferedReader = null;
        List<String> list =new ArrayList<String>();
        try {
            String encoding = getCharset(filePath);// 获取文件的编码格式
            File file = new File(filePath);
            reader = new InputStreamReader(new FileInputStream(file),encoding);
            bufferedReader = new BufferedReader(reader);
            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine()) != null){
                list.add(lineTxt);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
    private static String getCharset(String fileName) throws IOException{
        BufferedInputStream bin = null;
        bin = new BufferedInputStream(new FileInputStream(fileName));
        int p = (bin.read() << 8) + bin.read();

        String code = null;
        switch (p) {
            case 0xefbb:
                code = "UTF-8";
                break;
            case 0xfffe:
                code = "Unicode";
                break;
            case 0xfeff:
                code = "UTF-16BE";
                break;
            default:
                code = "GBK";
        }
        return code;
    }
}
